package com.zxw.controller;

import cn.hutool.core.date.DateUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.zxw.文件.PDF.util.PDFUtil;
import com.zxw.文件.PDF.util.TableCell;
import com.zxw.文件.PDF.util.WatermarkPageEvent;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @projectName: util-cloud
 * @package: com.zxw.controller
 * @className: PDFController
 * @author: zhangxuewei
 * @description: TODO
 * @date: 2023/9/8 9:52
 * @version: 1.0
 */
@RestController
@RequestMapping("/pdf")
public class PDFController {

    @GetMapping("/generate-pdf")
    public void generatePdf(HttpServletResponse response) throws IOException, DocumentException {
        // 设置响应内容类型为PDF
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=sample.pdf");

        // 设置中文字体，这里使用了 楷体常规
        BaseFont bf = BaseFont.createFont("c://windows//fonts//simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font font = new Font(bf, 12);


        // 创建PDF文档
        Document document = new Document();
        PdfWriter.getInstance(document, response.getOutputStream());
        // 打开文档
        document.open();
        // 添加中文内容
        Paragraph paragraph = new Paragraph("你好，iText 5！", font);
        document.add(paragraph);
        // 关闭文档
        document.close();
    }


    @GetMapping("/generate-pdf3")
    public void generatePdf3(HttpServletResponse response) throws IOException, DocumentException {
        // 设置响应内容类型为PDF
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=sample.pdf");

        // 设置中文字体，这里使用了 楷体常规
        BaseFont bf = BaseFont.createFont("c://windows//fonts//simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font font = new Font(bf, 12);

        // 创建PDF文档
        Document document = new Document();
        PdfWriter pdfWriter = PdfWriter.getInstance(document, response.getOutputStream());

        // 添加水印
        pdfWriter.setPageEvent(new WatermarkPageEvent("水印内容", PDFUtil.fontAddr));

        // 打开文档
        document.open();
        // 添加中文内容
        Paragraph paragraph = new Paragraph("你好，iText 5！", font);
        document.add(paragraph);

        font.setColor(BaseColor.GREEN);
        Paragraph paragraphc = new Paragraph("这是一个字体颜色为绿色的段落", font);
        document.add(paragraphc);

        Font font2 = new Font(bf, 18, Font.BOLD);
        Paragraph paragraph2 = new Paragraph("这是一个字体大小为18的粗体段落", font2);
        document.add(paragraph2);

        Font fontb = new Font(bf, 12);
        Chunk yellowChunk = new Chunk(" 这是一个背景颜色为黄色的段落 ", fontb);
        yellowChunk.setBackground(BaseColor.YELLOW);
        Paragraph paragraphcb = new Paragraph();
        paragraphcb.add(yellowChunk);
        document.add(paragraphcb);


        // 创建表格
        PdfPTable table = new PdfPTable(3); // 3列的表格
        table.setWidthPercentage(100);
        table.setSpacingBefore(10f);
        table.setSpacingAfter(10f);

        // 第一行数据
        PdfPCell cell1 = new PdfPCell(new Paragraph("列1"));
        cell1.setBorderColor(BaseColor.BLUE);
        cell1.setPadding(5);

        PdfPCell cell2 = new PdfPCell(new Paragraph("列2"));
        cell2.setBorderColor(BaseColor.RED);
        cell2.setPadding(5);

        PdfPCell cell3 = new PdfPCell(new Paragraph("列3"));
        cell3.setBorderColor(BaseColor.GREEN);
        cell3.setPadding(5);

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);


        document.add(table);

        // 关闭文档
        document.close();
    }


    /**
     * 导出考试记录列表
     */
    @SneakyThrows
    @PostMapping("/demo")
    public void exportPdf(HttpServletResponse response) {
        // 设置响应内容类型为PDF
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=sample.pdf");
        BaseFont bf = PDFUtil.getNormalBaseFont();
        Font font = PDFUtil.getNormalFont(bf);
        float fontSize = 14f;
        // 创建PDF文档
        Document document = new Document();
        PdfWriter pdfWriter = PdfWriter.getInstance(document, response.getOutputStream());

        // 写水印
        String info = " 水印内容  水印内容  水印内容  水印内容  水印内容  水印内容 ";
        for (int i = 0; i < 5; i++) {
            info += info;
        }
        pdfWriter.setPageEvent(new WatermarkPageEvent(info, PDFUtil.fontAddr));

        // 打开文档
        document.open();
        java.util.List<Map<Integer, TableCell>> data = new ArrayList<>();
        Map<Integer, TableCell> titleMap = new HashMap<>();
        titleMap.put(0, PDFUtil.tableCell);
        titleMap.put(1, new TableCell("标题", 30f, BaseColor.BLACK));
        titleMap.put(2, new TableCell("30", 30f, BaseColor.BLUE));

        data.add(titleMap);
        //书写标题和得分
        float[] widths = {100f, 200f, 100f};
        PDFUtil.writeTable(document, widths, bf, null, data);


        java.util.List<Map<Integer, TableCell>> baseInfo = new ArrayList<>();
        float[] baseInfoWidths = {70f, 100f, 70f, 100f, 70f, 100f};
        // 书写试卷基础信息
        Map<Integer, TableCell> baseInfoRow1 = new HashMap<>();
        baseInfoRow1.put(0, new TableCell("试卷状态", fontSize, BaseColor.BLACK).setCellBackgroundColor(new BaseColor(245, 245, 245)).setBold(true));
        baseInfoRow1.put(1, new TableCell("待批阅", fontSize, BaseColor.BLACK));
        baseInfoRow1.put(2, new TableCell("试卷总分", fontSize, BaseColor.BLACK).setCellBackgroundColor(new BaseColor(245, 245, 245)).setBold(true));
        baseInfoRow1.put(3, new TableCell("100", fontSize, BaseColor.BLACK));
        baseInfoRow1.put(4, new TableCell("及格线", fontSize, BaseColor.BLACK).setCellBackgroundColor(new BaseColor(245, 245, 245)).setBold(true));
        baseInfoRow1.put(5, new TableCell("60", fontSize, BaseColor.BLACK));

        baseInfo.add(baseInfoRow1);
        // 书写试卷基础信息
        Map<Integer, TableCell> baseInfoRow2 = new HashMap<>();
        baseInfoRow2.put(0, new TableCell("考试姓名", fontSize, BaseColor.BLACK).setCellBackgroundColor(new BaseColor(245, 245, 245)).setBold(true));
        baseInfoRow2.put(1, new TableCell("毛蒙蒙", fontSize, BaseColor.BLACK));
        baseInfoRow2.put(2, new TableCell("组织", fontSize, BaseColor.BLACK).setCellBackgroundColor(new BaseColor(245, 245, 245)).setBold(true));
        baseInfoRow2.put(3, new TableCell("留和医院", fontSize, BaseColor.BLACK));
        baseInfoRow2.put(4, new TableCell("部门", fontSize, BaseColor.BLACK).setCellBackgroundColor(new BaseColor(245, 245, 245)).setBold(true));
        baseInfoRow2.put(5, new TableCell("护理科", fontSize, BaseColor.BLACK));
        baseInfo.add(baseInfoRow2);
        PDFUtil.writeTable(document, baseInfoWidths, bf, BaseColor.BLACK, baseInfo);


        // 书写题目内容
        int qNo = 1;// 题目序号
        for (int i = 0; i < 7; i++) {
            // 书写题目类型
            if (i % 3 == 0) {
                PDFUtil.writeBoldParagraph(document, bf, null, "题目类型");
                PDFUtil.drawLine(document, 90, Element.ALIGN_RIGHT);
                qNo = 1;
            }

            // 书写题目内容（采用table布局）
            List<Map<Integer, TableCell>> qInfo = new ArrayList<>();
            Map<Integer, TableCell> qRow1 = new HashMap<>();
            qRow1.put(0, new TableCell(qNo + "、 题目：给定一个整数数组 nums 和一个目标值 target，请你在该数组中找出和为目标值的那 两个 整数，并返回他们的数组下标。(5)", fontSize, BaseColor.BLACK).setCellAlign(Element.ALIGN_LEFT));
            qNo++;
            if (i % 3 == 0) {// 正确的标蓝色
                qRow1.put(1, new TableCell(" 正确 得分:5", fontSize, new BaseColor(64, 158, 255)).setFontBackgroundColor(new BaseColor(235, 245, 255)));
            } else {// 错误的标红
                qRow1.put(1, new TableCell("  错误 得分:0", fontSize, new BaseColor(245, 108, 108)).setFontBackgroundColor(new BaseColor(253, 226, 226)));
            }
            qInfo.add(qRow1);
            float[] qWidths = {350f, 100f};
            PDFUtil.writeTable(document, qWidths, bf, null, qInfo);

            // 书写考生答案
            if (i % 3 == 0)
                PDFUtil.writeParagraph(document, font, null, " 考生作答：答案2");
            else
                PDFUtil.writeParagraph(document, font, null, " 考生作答：答案3");

            // 答案选项
            Paragraph paragraph = PDFUtil.getParagraph(font, fontSize);
            PDFUtil.appendWithBackgroundColor(paragraph, " 答案选项: ", null);
            for (int a = 0; a < 4; a++) {
                String content = "答案" + (a+1);

                BaseColor backgroundColor = new BaseColor(233, 233, 235);//默认浅灰色
                if (a == 1) {// 正确绿色
                    backgroundColor = new BaseColor(209, 237, 196);
                } else if (a == 2 && i % 3 != 0) {//错误红色
                    backgroundColor = new BaseColor(253, 226, 226);
                }
                if (a == (4 - 1)) { // 最后一个
                    PDFUtil.appendWithBackgroundColorEnd(paragraph, content, backgroundColor, document);
                } else {
                    PDFUtil.appendWithBackgroundColor(paragraph, content, backgroundColor);
                    PDFUtil.appendWithBackgroundColor(paragraph, "  ", null);
                }
            }
        }

        // 关闭文档
        document.close();
    }

}
